import { Hub } from "@/func";
import { TimeOfDay, world } from "@minecraft/server";
import { PlayerGroup } from "@sapi-game/gamePlayer/playerGroup";
import { WereWolfContext } from "./context";
import { WereWolfMapData } from "./maps";
import { WereWolfIDDb, WereWolfModule } from "./module";
import { WereWolfPickNumberState } from "./pickNumberState/state";
import { WereWolfPlayer } from "./player";
import { WereWolfNoColor } from "./static";

export class WereWolfGame extends WereWolfModule.Engine<{
    map: WereWolfMapData;
}> {
    protected override buildContext(config: {
        map: WereWolfMapData;
    }): WereWolfContext {
        return new WereWolfContext(new PlayerGroup(WereWolfPlayer), {
            map: config.map,
        });
    }

    override onStart(): void {
        this.pushState(WereWolfPickNumberState);
    }

    override onStop(): void {
        if (this.context.day != 0) {
            this.showResult();
        }
        world.setTimeOfDay(TimeOfDay.Day);
        this.context.players.forEach((p) => Hub(p.player));
        WereWolfIDDb.dispose();
    }

    showResult() {
        let msg = "本局游戏结果：\n";
        const players = this.context.players
            .filter((p) => p.role != undefined)
            .sort((a, b) => a.no - b.no);
        players.forEach((p) => {
            msg += `${WereWolfNoColor[p.no - 1]}[${p.no}号]§r${p.name} - §r${
                p.role
            }§r - ${p.dead ? "阵亡" : "存活"}\n`;
        });
        this.context.players.sendMessage(msg);
    }
}
